<?php

namespace App\Http\Controllers\Admin\Base;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AgentCostModel;
use App\Models\AgentModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class Agent extends Controller
{

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $name = $request->input('name', '');
        $type = $request->input('type', '');
        $create_start = $request->input('startTime', '');
        $create_end = $request->input('endTime', '');

        $query = AgentModel::query()->with('create_admin');

        if($name){
            $query = $query->where('name', 'like', "%$name%");
        }

        if($type){
            $query = $query->where('type', $type);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'type' => $item->type,
                'type_name' => AgentModel::TYPE_LIST[$item->type] ?? '',
                'name' => $item->name,
                'created_at' => $item->created_at->toDateTimeString(),
                'create_user' => $item->create_admin->staff->name ?? '',
                'account_name' => $item->account_name,
                'bank' => $item->bank,
                'bank_card' => $item->bank_card,
                'cost' => $item->cost,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();
        $validator = Validator::make($params, [
            'type' => 'required',
            'name' => 'required',
            'cost' => 'array',
            'cost.*.type' => 'required',
            'cost.*.price' => 'required',
        ], [
            'type.required' => '请选择服务提供商类型',
            'name.required' => '请选择角色',
            'cost.array' => '请填写费用',
            'cost.*.type.required' => '请选择费用类型',
            'cost.*.price.required' => '请填写费用',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        DB::beginTransaction();
        try{
            $agent = new AgentModel();
            $agent->type = $params['type'];
            $agent->name = $params['name'];
            $agent->created_admin_id = $auth->id;
            $agent->save();

            foreach($params['cost'] as $cost) {
                $cost_model = new AgentCostModel();
                $cost_model->agent_id = $agent->id;
                $cost_model->type = $cost['type'];
                $cost_model->price = $cost['price'];
                $cost_model->currency = $cost['currency'] ?? '';
                $cost_model->creator_id = $auth->id;
                $cost_model->save();
            }

            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function update(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $id = $params['id'] ?? false;
        if($id === false) {
            return $this->error('缺少参数');
        }

        $validator = Validator::make($params, [
            'type' => 'required',
            'name' => 'required',
            'cost' => 'array',
            'cost.*.type' => 'required',
            'cost.*.price' => 'required',
        ], [
            'type.required' => '请选择服务提供商类型',
            'name.required' => '请选择角色',
            'cost.array' => '请填写费用',
            'cost.*.type.required' => '请选择费用类型',
            'cost.*.price.required' => '请填写费用',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }

        $agent = AgentModel::find($id);
        if(!$agent) {
            return $this->error('服务提供商不存在');
        }

        DB::beginTransaction();
        try{
            $agent->type = $params['type'];
            $agent->name = $params['name'];
            $agent->save();

            AgentCostModel::where('agent_id', $agent->id)->delete();
            foreach($params['cost'] as $cost) {
                $cost_model = new AgentCostModel();
                $cost_model->agent_id = $agent->id;
                $cost_model->type = $cost['type'];
                $cost_model->price = $cost['price'];
                $cost_model->currency = $cost['currency'] ?? '';
                $cost_model->save();
            }

            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //付款账户
    public function bank_account(Request $request) {
        $params = $request->all();
        $validator = Validator::make($params, [
            'id' => 'required',
            'account_name' => 'required',
            'bank' => 'required',
            'bank_card' => 'required',
        ], [
            'id.required' => '缺少参数',
            'account_name.required' => '请填写账户名称',
            'bank.required' => '请填写银行',
            'bank_card.required' => '请填写银行卡号',
        ]);

        if ($validator->fails()) {
            $err = $validator->errors()->first();
            return $this->error($err);
        }


        $agent = AgentModel::find($params['id']);
        if(!$agent) {
            return $this->error('服务提供商不存在');
        }

        $agent->account_name = $params['account_name'];
        $agent->bank = $params['bank'];
        $agent->bank_card = $params['bank_card'];
        $agent->save();

        return $this->success();
    }

    public function delete(int $id){
        $agent = AgentModel::find($id);
        if(!$agent) {
            return $this->error('服务提供商不存在');
        }
        $agent->delete();
        return $this->success();
    }

}
